<template>
  <div flex flex-col style="height: 100%;">
    <div
      style="background: var(--bg-builtin);"
      px4 h="3rem" flex items-center>
      <el-button type="primary" plain size="small" :icon="ElIconPlus" @click="newTrigger">
        新触发
      </el-button>
      <div mlauto mr1>启用</div>
      <el-switch :before-change="toggleTrigger" v-model="isTriggerActive"/>
    </div>
    <input type="text" ref="triggerKeyInput" style="width: 0px;height: 0px; opacity: 0;" @keydown="setKey">
    
    <div p4 flex-1>
      <el-table :border="true" :data="oProject.trainerTriggers" style="width: 600px; height: 100%;" mb>
        <el-table-column prop="name" label="#" width="60">
          <template #default="scope">
            <div>{{ scope.$index }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="按键" width="150">
          <template #default="scope">
            <div v-if="activeKeyIndex==scope.$index" text-amber>请按键</div>
            <el-button v-else @click="onSetKey(scope.$index)">{{ toUpper(scope.row.key) ||'未设置' }}</el-button>
            <!-- {{ scope.row }} -->
          </template>
        </el-table-column>
        <el-table-column prop="name" label="动作" width="150">
          <template #default="scope">
            <el-select
              v-model="scope.row.graphName"
              value-key="name"
              placeholder="Select"
              size="small"
              style="width: 120px"
            >
              <el-option
                v-for="(item, index) in oProject.graphs"
                :key="index"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="操作">
          <template #default="scope">
            <el-button size="small" type="danger" @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    
  </div>
</template>

<script setup lang="ts">
import { TrainerTrigger } from '~/models/Trainer/TrainerTrigger';
import { useLocalStorage } from '@vueuse/core';
import { toUpper } from 'lodash';
import { Graph } from '~/models/graph/graph';
import type { GamePoint } from '~/models/Game/GamePoint';
import { oProject } from '~/models/Project';
import { defaultTaskManager } from '~/models/Task/TaskManager';

const triggerKeyInput = ref(null as null | HTMLElement)
const recording = ref(false)
// const triggers = ref([] as TrainerTrigger[])
// const triggersBak = useLocalStorage('tab-trigger-triggers', '[]')
// watch(triggers, val => {
//   triggersBak.value = JSON.stringify(val)
// },{
//   deep: true,
// })

const activeKeyIndex = ref(-1)
function onSetKey(index: number) {
  activeKeyIndex.value = index
  triggerKeyInput.value?.focus()
}
function setKey(e: KeyboardEvent) {
  console.log(e.key);
  oProject.value.trainerTriggers[activeKeyIndex.value].key = e.key
  activeKeyIndex.value = -1
  triggerKeyInput.value?.blur()
}

async function newTrigger() {
  oProject.value.trainerTriggers.push(new TrainerTrigger())
}

function onMove(point: GamePoint) {

}

function onDelete(item: TrainerTrigger) {
  remove(oProject.value.trainerTriggers, x => x === item)
}

const triggers = computed(() => oProject.value.trainerTriggers)
const processId = ref('')


const isTriggerActive = useLocalStorage('tab-trigger-isTriggerActive', false)
async function toggleTrigger() {
  let success = false
  if (isTriggerActive.value) {
    // 关闭
    const result = await defaultTaskManager.value.stop(processId.value)
    success = result.success
  }
  else {
    // 打开
    const code = TrainerTrigger.compileAll(oProject.value.trainerTriggers)
    console.log(code);
    const result = await defaultTaskManager.value.start(code)
    processId.value = result.message!
    success = result.success
  }
  
  return success
}
</script>